# coding = utf-8

'''
分析gabor filter滤波之后的结果
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math
from skimage import measure






def garbor_filter_v2(image):
    image = image * 255
    image = image.astype(np.uint8)

    filters3 = []
    theta2 = [0, 1 * np.pi / 4, 2 * np.pi / 4, 3 * np.pi / 4]
    for item in theta2:
        kern = cv2.getGaborKernel((3, 3), sigma=1.5, theta=item, lambd=3, gamma=1.2, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = []
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        accum = cv2.equalizeHist(accum)
        result3.append(accum)
    result3.append(cv2.equalizeHist(image))
    return result3

def garbor_filter(image):

    image = image * 255
    image = image.astype(np.uint8)

    temp = np.zeros(image.shape)

    filters1 = []
    lamda = [2, 3, 4, 5, 6, 7]
    for item in lamda:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=0, lambd=item, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters1.append(kern)
    result1 = np.zeros_like(temp)
    for i in range(len(filters1)):
        accum = np.zeros_like(image)
        for kern in filters1[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result1 += np.array(accum)
    result1 = result1/len(filters1)
    result1 = result1.astype(np.uint8)
    result1 = cv2.equalizeHist(result1)

    filters2 = []
    theta1 = [0, 1 * np.pi / 4, 2 * np.pi / 4, 3 * np.pi / 4]
    for item in theta1:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi/2.0 , gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters2.append(kern)
    result2 = np.zeros_like(temp)
    for i in range(len(filters2)):
        accum = np.zeros_like(image)
        for kern in filters2[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result2 += np.array(accum)
    result2 = result2 / len(filters2)
    result2 = result2.astype(np.uint8)
    result2 = cv2.equalizeHist(result2)

    filters3 = []
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi / 6]
    for item in theta2:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi/2.0, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = np.zeros_like(temp)
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result3 += np.array(accum)
    result3 = result3 / len(filters3)
    result3 = result3.astype(np.uint8)
    result3 = cv2.equalizeHist(result3)

    filters4 = []
    lamda = [2, 3, 4, 5, 6, 7]
    for item in lamda:
        kern = cv2.getGaborKernel((7, 7), sigma=1.0, theta=0, lambd=item, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters4.append(kern)
    result4 = np.zeros_like(temp)
    for i in range(len(filters4)):
        accum = np.zeros_like(image)
        for kern in filters4[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result4 += np.array(accum)
    result4 = result4 / len(filters4)
    result4 = result4.astype(np.uint8)
    result4 = cv2.equalizeHist(result4)

    filters5 = []
    theta1 = [0, 1 * np.pi / 4, 2 * np.pi / 4, 3 * np.pi / 4]
    for item in theta1:
        kern = cv2.getGaborKernel((7, 7), sigma=1.0, theta=item, lambd=5, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters5.append(kern)
    result5 = np.zeros_like(temp)
    for i in range(len(filters5)):
        accum = np.zeros_like(image)
        for kern in filters5[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result5 += np.array(accum)
    result5 = result5 / len(filters5)
    result5 = result5.astype(np.uint8)
    result5 = cv2.equalizeHist(result5)


    filters6 = []
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi / 6]
    for item in theta2:
        kern = cv2.getGaborKernel((7, 7), sigma=1.0, theta=item, lambd=5, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters6.append(kern)
    result6 = np.zeros_like(temp)
    for i in range(len(filters6)):
        accum = np.zeros_like(image)
        for kern in filters6[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result6 += np.array(accum)
    result6 = result6 / len(filters6)
    result6 = result6.astype(np.uint8)
    result6 = cv2.equalizeHist(result6)

    result = [result1, result2, result3, result4, result5, result6]
    result = np.array(result)
    result = result.astype(np.uint8)
    #result = result.astype(np.float32)
    #result = result / 255.

    return result

def garbor_filter3(image):
    image = image * 255
    image = image.astype(np.uint8)
    #image = cv2.equalizeHist(image)

    filters = []
    ksize = [7]  # gabor尺度，6个
    #lamda = np.pi / 2.0  # 波长
    lamda = 5
    for theta in np.arange(0, np.pi, np.pi / 4):  # gabor方向，0°，45°，90°，135°，共四个
        for K in range(len(ksize)):
            kern = cv2.getGaborKernel((ksize[K], ksize[K]), 1.0, theta, lamda, 0.5, 0, ktype=cv2.CV_32F)
            kern /= 1.5 * kern.sum()
            filters.append(kern)

    size = int(math.sqrt(len(filters))) + 1
    for temp in range(len(filters)):
        plt.subplot(size, size, temp + 1)
        plt.imshow(filters[temp], cmap="gray")
    plt.show()

    result = np.zeros(image.shape)

    for i in range(len(filters)):
        # res1 = process(img, filters[i])
        accum = np.zeros_like(image)
        for kern in filters[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        print(np.min(np.array(accum)), np.max(np.array(accum)))
        result += np.asarray(accum)

    result = result/len(filters)
    result = result.astype(np.uint8)
    #result = cv2.equalizeHist(result)
    print(np.min(result), np.max(result))

    return [result, cv2.equalizeHist(image)]


def garbor_filter4(image):
    image = image * 255
    image = image.astype(np.uint8)

    temp = np.zeros(image.shape)

    filters3 = []
    #theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi / 6]
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi/6]
    for item in theta2:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi / 2.0, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        #kern = cv2.getGaborKernel((10, 10), sigma=1.0, theta=item, lambd=5, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = np.zeros_like(temp)
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result3 += np.array(accum)
    result3 = result3 / len(filters3)
    result3 = result3.astype(np.uint8)
    #clahe = cv2.createCLAHE(clipLimit=5, tileGridSize=(100, 100))
    result3 = cv2.equalizeHist(result3)
    #result3 = clahe.apply(result3)

    return result3




def read_data():

    def find_data(case_id, origion_id, index):
         big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
         big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
         big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
         big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
         big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
         big_image[big_image<=-200] = -200
         big_image[big_image > 250] = 250
         big_image = (big_image+200) / 450
         big_image = big_image[index]
         big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
         big_liver = big_liver[index]
         big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
         big_tumor = big_tumor[index]
         big_fusion = Image.open(big_fusion)
         return (big_image, big_fusion, big_liver, big_tumor)

    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=74, origion_id="0656", index=40)
    (middle_image, middle_fusion, middle_liver, middle_tumor) = find_data(case_id=67, origion_id="0415", index=135)
    (small_image, small_fusion, small_liver, small_tumor) = find_data(case_id=79, origion_id="0865", index=262)
    (little_image, little_fusion, little_liver, little_tumor) = find_data(case_id=72, origion_id="0628", index=142)

    print("big")
    result = garbor_filter(big_image)
    big_liver = np.zeros(big_image.shape)
    big_liver[big_image>0] = 1
    plt.subplot(1, 3, 1)
    plt.title("raw image")
    plt.imshow(big_fusion)
    plt.subplot(1, 3, 2)
    plt.title("kernel=2")
    plt.imshow((255 - result[0])*big_liver, cmap="gray")
    plt.subplot(1, 3, 3)
    plt.title("kernet=7")
    plt.imshow((255-result[1])*big_liver, cmap="gray")
    plt.show()


    print("middle")
    result = garbor_filter(middle_image)
    middle_liver = np.zeros(middle_image.shape)
    middle_liver[middle_image>0] = 1
    plt.subplot(1, 3, 1)
    plt.title("raw image")
    plt.imshow(middle_fusion)
    plt.subplot(1, 3, 2)
    plt.title("kernel=2")
    plt.imshow((255-result[0])*middle_liver, cmap="gray")
    plt.subplot(1, 3, 3)
    plt.title("kernet=7")
    plt.imshow((255-result[1])*middle_liver, cmap="gray")
    plt.show()

    print("small")
    result = garbor_filter(small_image)
    small_liver = np.zeros(small_image.shape)
    small_liver[small_image>0] = 1
    plt.subplot(1, 3, 1)
    plt.title("raw image")
    plt.imshow(small_fusion)
    plt.subplot(1, 3, 2)
    plt.title("kernel=2")
    plt.imshow((255-result[0])*small_liver, cmap="gray")
    plt.subplot(1, 3, 3)
    plt.title("kernet=7")
    plt.imshow((255-result[1])*small_liver, cmap="gray")
    plt.show()

    print("little")
    result = garbor_filter(little_image)
    little_liver = np.zeros(little_image.shape)
    little_liver[little_image>0] = 1
    plt.subplot(1, 3, 1)
    plt.title("raw image")
    plt.imshow(little_fusion)
    plt.subplot(1, 3, 2)
    plt.title("kernel=2")
    plt.imshow((255-result[0])*little_liver, cmap="gray")
    plt.subplot(1, 3, 3)
    plt.title("kernet=7")
    plt.imshow((255-result[1])*little_liver, cmap="gray")
    plt.show()


def read_data_v3():
    def find_data(case_id, origion_id, index):
        big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
        big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
        big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
        big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
        big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
        big_image[big_image <= -200] = -200
        big_image[big_image > 250] = 250
        big_image = (big_image + 200) / 450
        big_image = big_image[index]
        big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
        big_liver = big_liver[index]
        big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
        big_tumor = big_tumor[index]
        big_fusion = Image.open(big_fusion)
        return (big_image, big_fusion, big_liver, big_tumor)

    (small_image1, small_fusion1, small_liver1, small_tumor1) = find_data(case_id=72, origion_id="0628", index=141)
    (small_image, small_fusion, small_liver, small_tumor) = find_data(case_id=72, origion_id="0628", index=142)
    (small_image2, small_fusion2, small_liver2, small_tumor2) = find_data(case_id=72, origion_id="0628", index=143)

    result1 = garbor_filter(small_image1)
    result = garbor_filter(small_image)
    result2 = garbor_filter(small_image2)

    plt.subplot(3, 3, 1)
    plt.imshow(small_fusion1)
    plt.subplot(3, 3, 2)
    plt.imshow(small_fusion)
    plt.subplot(3, 3, 3)
    plt.imshow(small_fusion2)

    plt.subplot(3, 3, 4)
    plt.imshow((255-result1[0])*small_liver1, cmap="gray")
    plt.subplot(3, 3, 5)
    plt.imshow((255-result[0])*small_liver, cmap="gray")
    plt.subplot(3, 3, 6)
    plt.imshow((255-result2[0])*small_liver2, cmap="gray")

    plt.subplot(3, 3, 7)
    plt.imshow((255-result1[1])*small_liver1, cmap="gray")
    plt.subplot(3, 3, 8)
    plt.imshow((255-result[1])*small_liver, cmap="gray")
    plt.subplot(3, 3, 9)
    plt.imshow((255-result2[1])*small_liver2, cmap="gray")

    plt.show()


def read_data_v4():
    def find_data(case_id, origion_id, index):
        big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
        big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
        big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
        big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
        big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
        big_image[big_image <= -200] = -200
        big_image[big_image > 250] = 250
        big_image = (big_image + 200) / 450
        big_image = big_image[index]
        big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
        big_liver = big_liver[index]
        big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
        big_tumor = big_tumor[index]
        big_fusion = Image.open(big_fusion)
        return (big_image, big_fusion, big_liver, big_tumor)

    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=79, origion_id="0865", index=262)

    #garbor_filter4(big_image*big_liver)

    #big_liver_dilated = big_liver * 255
    #big_liver_dilated = big_liver_dilated.astype(np.uint8)
    #kernel = np.ones((5, 5), np.uint8)
    #big_liver_dilated = cv2.dilate(big_liver_dilated, kernel=kernel)
    #big_liver_dilated[big_liver_dilated>0] = 1

    big_tumor[big_tumor > 0] = 1
    big_tumor = big_tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    #big_image = big_image * big_liver
    #temp = garbor_filter4(big_image * big_liver)
    #temp = temp.astype(np.uint8)
    #temp = cv2.equalizeHist(temp)
    #temp = (255 - temp) * big_liver

    liver = (big_image)*big_liver
    liver = liver * 255
    liver = liver.astype(np.uint8)
    #liver = cv2.equalizeHist(liver)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    garbor_result = garbor_filter4(big_image*big_liver)
    image = cv2.cvtColor(garbor_result, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(image, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)


    data = cv2.medianBlur((255 - garbor_result) * big_liver, ksize=5)




    #data = cv2.blur((255 - garbor_result) * big_liver, ksize=(3,3))
    #data = (255 - garbor_result) * big_liver

    data[data <= 200] = 0
    data[data > 200] = 1


    liver_t = np.zeros(data.shape)
    temp = big_image*big_liver
    liver_t += (temp*data)
    liver_t += (temp*(1-data)*1.2)
    liver_t = liver_t/1.2
    liver_t = liver_t * 255
    liver_t = liver_t.astype(np.uint8)
    liver_t = cv2.cvtColor(liver_t, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver_t, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    [data_labels, num] = measure.label(data, return_num=True)

    for i in np.unique(data_labels):
        if (data_labels == i).sum() < 1000 or i == 0:
            continue
        temp = np.zeros(data_labels.shape)
        temp[data_labels == i] = 1
        fp = 1 - float((big_tumor[temp == 1]>0).sum())/float((temp == 1).sum())
        print(i, format(fp, ".2f"))


    plt.subplot(2, 2, 1)
    plt.title("origion image")
    plt.imshow(liver)
    plt.subplot(2, 2, 2)
    plt.title("gabor enhance")
    plt.imshow(liver_t)
    plt.subplot(2, 2, 3)
    plt.title("mask")
    plt.imshow(data, cmap="gray")
    plt.subplot(2, 2, 4)
    plt.title("region")
    plt.imshow(image)
    plt.show()





if __name__ == '__main__':
    read_data_v4()